package com.weike.yuanding.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.weike.yuanding.VideoApplication;
import com.weike.yuanding.constant.UserVideoRelationEnum;
import com.weike.yuanding.constant.VideoStatusEnum;
import com.weike.yuanding.core.domain.R;
import com.weike.yuanding.dto.user.UserDTO;
import com.weike.yuanding.entity.UserVideoRelationEntity;
import com.weike.yuanding.entity.VideoMainEntity;
import com.weike.yuanding.entity.VideoReviewEntity;
import com.weike.yuanding.feign.user.UserService;
import com.weike.yuanding.mapper.UserVideoRelationMapper;
import com.weike.yuanding.mapper.VideoMainMapper;
import com.weike.yuanding.mapper.VideoReviewMapper;
import com.weike.yuanding.service.VideoService;
import com.weike.yuanding.utils.BaseContext;
import com.weike.yuanding.vo.ReviewResVo;
import com.weike.yuanding.vo.VideoResVo;
import com.weike.yuanding.vo.VideoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: VideoServiceImpl
 * @Author: YuanDing
 * @Date: 2025/4/5 17:08
 * @Description:
 */

@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideoMainMapper videoMainMapper;

    @Autowired
    private UserVideoRelationMapper userVideoRelationMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private VideoReviewMapper videoReviewMapper;


    @Override
    public List<VideoResVo> list(List<String> videoIds) {
        if (videoIds.isEmpty()) {
            return new ArrayList<VideoResVo>();
        }
        String userId = BaseContext.userId.get();

        List<VideoMainEntity> videoMainEntityList = videoMainMapper
                .selectList(new LambdaQueryWrapper<VideoMainEntity>()
                .in(VideoMainEntity::getVideoId, videoIds));


        return getVideoResVos(videoMainEntityList, userId);
    }

    private ArrayList<VideoResVo> getVideoResVos(List<VideoMainEntity> videoMainEntityList, String userId) {
        ArrayList<VideoResVo> resVoArrayList = new ArrayList<>();
        for (VideoMainEntity videoMainEntity : videoMainEntityList) {
            String videoId = videoMainEntity.getVideoId();
            VideoResVo videoResVo = new VideoResVo();
            BeanUtils.copyProperties(videoMainEntity , videoResVo);
            // 获取点赞数量、收藏数量、分享数量、评论数
            videoResVo.setReviewNumber(
                    videoReviewMapper.selectCount(new LambdaQueryWrapper<VideoReviewEntity>()
                            .eq(VideoReviewEntity::getVideoId , videoId))
            );


            videoResVo.setLikeNumber(userVideoRelationMapper
                    .selectCount(new LambdaQueryWrapper<UserVideoRelationEntity>()
                            .eq(UserVideoRelationEntity::getVideoId , videoId)
                            .eq(UserVideoRelationEntity::getType, UserVideoRelationEnum.LIKE.getCode())));

            videoResVo.setShouCangNumber(userVideoRelationMapper
                    .selectCount(new LambdaQueryWrapper<UserVideoRelationEntity>()
                            .eq(UserVideoRelationEntity::getVideoId , videoId)
                            .eq(UserVideoRelationEntity::getType, UserVideoRelationEnum.SHOU_CANG.getCode())
                            ));

            videoResVo.setFenXiangNumber(userVideoRelationMapper
                    .selectCount(new LambdaQueryWrapper<UserVideoRelationEntity>()
                            .eq(UserVideoRelationEntity::getVideoId , videoId)
                            .eq(UserVideoRelationEntity::getType, UserVideoRelationEnum.FEN_XIANG.getCode())
                    ));


            videoResVo.setIsShouCang(userVideoRelationMapper
                    .selectCount(new LambdaQueryWrapper<UserVideoRelationEntity>()
                            .eq(UserVideoRelationEntity::getVideoId , videoId)
                            .eq(UserVideoRelationEntity::getType, UserVideoRelationEnum.SHOU_CANG.getCode())
                            .eq(UserVideoRelationEntity::getUserId , userId)) > 0);

            videoResVo.setIsLiked(userVideoRelationMapper
                    .selectCount(new LambdaQueryWrapper<UserVideoRelationEntity>()
                            .eq(UserVideoRelationEntity::getVideoId , videoId)
                            .eq(UserVideoRelationEntity::getType, UserVideoRelationEnum.LIKE.getCode())
                            .eq(UserVideoRelationEntity::getUserId , userId)) > 0);

/*            videoResVo.setIsGuanZhu(userVideoRelationMapper
                    .selectCount(new LambdaQueryWrapper<UserVideoRelationEntity>()
                            .eq(UserVideoRelationEntity::getVideoId , videoId)
                            .eq(UserVideoRelationEntity::getType, UserVideoRelationEnum.GUAN_ZHU.getCode())
                            .eq(UserVideoRelationEntity::getUserId , userId)) > 0);*/

            R<UserDTO> userResult = userService.getUserInfoById(videoMainEntity.getUserId() , userId);
            UserDTO user = userResult.getData();
            videoResVo.setIsGuanZhu(user.getIsGuanZhu());
            videoResVo.setAuthorAvatar(user.getAvatar());
            videoResVo.setAuthorName(user.getName());
            videoResVo.setAuthorId(user.getUserId());
            videoResVo.setAuthorId(user.getUserId());
            resVoArrayList.add(videoResVo);
        }
        return resVoArrayList;
    }

    @Override
    public List<VideoResVo> listById(VideoVo videoVo) {
        String userId = BaseContext.userId.get();

        List<VideoMainEntity> videoMainEntities = videoMainMapper.selectList(new LambdaQueryWrapper<VideoMainEntity>()
                .eq(VideoMainEntity::getUserId, videoVo.getUserId()));
        return getVideoResVos(videoMainEntities, videoVo.getUserId());
    }

    @Override
    public List<ReviewResVo> reviewList(VideoVo videoVo) {

        String currentUserId = BaseContext.userId.get();


        List<VideoReviewEntity> videoReviewEntities = videoReviewMapper.selectList(new LambdaQueryWrapper<VideoReviewEntity>()
                .eq(VideoReviewEntity::getVideoId, videoVo.getVideoId())
                .orderByDesc(VideoReviewEntity :: getCreateTime)
        );

        // 排序：当前用户的评论排最前，其它仍按时间倒序
        videoReviewEntities.sort((a, b) -> {
            boolean aIsCurrentUser = currentUserId.equals(a.getUserId());
            boolean bIsCurrentUser = currentUserId.equals(b.getUserId());

            if (aIsCurrentUser && !bIsCurrentUser) {
                return -1;
            } else if (!aIsCurrentUser && bIsCurrentUser) {
                return 1;
            } else {
                return b.getCreateTime().compareTo(a.getCreateTime());
            }
        });

        List<ReviewResVo> reviewResVoList = videoReviewEntities.stream().map(item -> {
            ReviewResVo reviewResVo = new ReviewResVo();
            reviewResVo.setId(item.getReviewId());

            R<UserDTO> userInfoById = userService.getUserInfoById(item.getUserId() , currentUserId);
            UserDTO user = userInfoById.getData();
            reviewResVo.setAuthor(user.getName());
            reviewResVo.setAvatar(user.getAvatar());
            reviewResVo.setDatetime(item.getCreateTime());
            reviewResVo.setContent(item.getReview());
            return reviewResVo;
        }).collect(Collectors.toList());


        return reviewResVoList;
    }
}
